package com.chushouya.manager.service.api.impl;

import com.chushouya.common.util.PasswordUtil;
import com.chushouya.manager.dao.entity.UserEntity;
import com.chushouya.manager.dao.entity.UserExtendEntity;
import com.chushouya.manager.dao.repository.UserRepository;
import com.chushouya.manager.dao.repository.UserExtendRepository;
import com.chushouya.manager.dto.admin.user.UserCenterDTO;
import com.chushouya.manager.dto.admin.user.password.SetPasswordDTO;
import com.chushouya.manager.dto.admin.user.password.UpdatePasswordDTO;
import com.chushouya.manager.service.api.UserCenterApiService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.lang.Validate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户中心接口服务实现类
 * 提供用户中心相关数据查询功能
 * 
 * @author chushouya
 */
@Service
public class UserCenterApiServiceImpl implements UserCenterApiService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserExtendRepository userExtendRepository;

    @Override
    public UserCenterDTO getUserCenter(Long userId) {
        Validate.isNull(userId, "用户ID不能为空");
        
        // 查询用户基本信息
        UserEntity userEntity = userRepository.selectByPrimaryKey(userId);
        Validate.isNull(userEntity, "用户不存在");
        
        // 转换为返回DTO
        UserCenterDTO userCenterDTO = new UserCenterDTO();
        userCenterDTO.setUserId(userEntity.getUserId());
        userCenterDTO.setNickName(userEntity.getUserName());
        userCenterDTO.setUserName(userEntity.getUserName());
        userCenterDTO.setUserPhone(userEntity.getUserPhone());
        
        return userCenterDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setPassword(Long userId, SetPasswordDTO dto) {
        Validate.isNull(userId, "用户ID不能为空");
        
        // 查询用户信息
        UserEntity userEntity = userRepository.selectByPrimaryKey(userId);
        if (Objects.isNull(userEntity)) {
            throw Ex.business("用户不存在");
        }
        
        // 检查是否已设置密码
        if (Strings.isNotBlank(userEntity.getPassword())) {
            throw Ex.business("密码已设置，请使用修改密码功能");
        }
        
        // 验证两次密码是否一致
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw Ex.business("两次输入的密码不一致");
        }
        
        // 密码长度验证
        if (dto.getPassword().length() < 6 || dto.getPassword().length() > 20) {
            throw Ex.business("密码长度必须在6-20位之间");
        }
        
        // 更新密码
        UserEntity update = new UserEntity();
        update.setUserId(userId);
        update.setPassword(PasswordUtil.encryptPassword(dto.getPassword()));
        update.setUpdateTime(new Date());
        userRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Long userId, UpdatePasswordDTO dto) {
        Validate.isNull(userId, "用户ID不能为空");
        
        // 查询用户信息
        UserEntity userEntity = userRepository.selectByPrimaryKey(userId);
        if (Objects.isNull(userEntity)) {
            throw Ex.business("用户不存在");
        }
        
        // 检查是否已设置密码
        if (Strings.isBlank(userEntity.getPassword())) {
            throw Ex.business("未设置密码，请先设置密码");
        }
        
        // 验证原密码
        if (!PasswordUtil.matchesPassword(dto.getOldPassword(), userEntity.getPassword())) {
            throw Ex.business("原密码错误");
        }
        
        // 验证两次密码是否一致
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw Ex.business("两次输入的密码不一致");
        }
        
        // 验证新密码不能与旧密码相同
        if (PasswordUtil.matchesPassword(dto.getPassword(), userEntity.getPassword())) {
            throw Ex.business("新密码不能与旧密码相同");
        }
        
        // 密码长度验证
        if (dto.getPassword().length() < 6 || dto.getPassword().length() > 20) {
            throw Ex.business("密码长度必须在6-20位之间");
        }
        
        // 更新密码
        UserEntity update = new UserEntity();
        update.setUserId(userId);
        update.setPassword(PasswordUtil.encryptPassword(dto.getPassword()));
        update.setUpdateTime(new Date());
        userRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAccount(Long userId) {
        Validate.isNull(userId, "用户ID不能为空");
        
        // 查询用户信息
        UserEntity userEntity = userRepository.selectByPrimaryKey(userId);
        if (Objects.isNull(userEntity)) {
            throw Ex.business("用户不存在");
        }
        
        // 检查用户是否已经注销
        if (userEntity.getStatus() != null && userEntity.getStatus() == -1) {
            throw Ex.business("用户已注销");
        }
        
        // 更新用户主表：用户名、手机号加上-99后缀，status改为-1
        UserEntity update = new UserEntity();
        update.setUserId(userId);
        
        // 用户名加上-99后缀
        if (Strings.isNotBlank(userEntity.getUserName())) {
            update.setUserName(userEntity.getUserName() + "-99");
        }
        
        // 手机号加上-99后缀
        if (Strings.isNotBlank(userEntity.getUserPhone())) {
            update.setUserPhone(userEntity.getUserPhone() + "-99");
        }
        
        // 状态改为-1
        update.setStatus(-1);
        update.setUpdateTime(new Date());
        
        userRepository.updateByPrimaryKeySelective(update);
        
        // 更新用户扩展表：openid加上-99后缀
        List<UserExtendEntity> extendList = userExtendRepository.selectListByUserId(userId);
        if (extendList != null && !extendList.isEmpty()) {
            for (UserExtendEntity extendEntity : extendList) {
                UserExtendEntity extendUpdate = new UserExtendEntity();
                extendUpdate.setUserExtendId(extendEntity.getUserExtendId());
                
                // openid加上-99后缀
                if (Strings.isNotBlank(extendEntity.getOpenId())) {
                    extendUpdate.setOpenId(extendEntity.getOpenId() + "-99");
                }
                
                extendUpdate.setUpdateTime(new Date());
                userExtendRepository.updateByPrimaryKeySelective(extendUpdate);
            }
        }
    }
}
